package com.zl.learning.arithmetic.my;

import static com.zl.learning.arithmetic.util.SortUtil.getRandomArray;
import static com.zl.learning.arithmetic.util.SortUtil.printArray;

public class MergeSort {

    public static void main(String[] args) {
        int[] a = getRandomArray(9);
//        int[] a = {8, 4, 5, 7, 1, 3, 6, 2};
        printArray(a);
        sort(a);
        printArray(a);
    }

    private static void sort(int[] arr) {
        int[] temp = new int[arr.length];
        sort(arr, 0, arr.length - 1, temp);
    }

    private static void sort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            sort(arr, left, mid, temp);
            sort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    private static void merge(int[] a, int left, int mid, int right, int[] temp) {
        int i = left, j = mid + 1, t = 0;
        while (i <= mid && j <= right) {
            if (a[i] < a[j]) {
                temp[t++] = a[i++];
            } else {
                temp[t++] = a[j++];
            }
        }
        while (i <= mid) {
            temp[t++] = a[i++];
        }
        while (j <= right) {
            temp[t++] = a[j++];
        }
        t = 0;
        while (left <= right) {
            a[left++] = temp[t++];
        }
    }

}
